import threading
import socket
import time


class SnakeSock:
    """
    1. send和recv这两个方法都需要一直执行下去。
    """
    def __init__(self):
        self.state = None
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.IP = '<broadcast>'
        self.PORT = 8888
        self.ADDRESS = (self.IP, self.PORT)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.bind(self.ADDRESS)

        self.lock = threading.Lock()
        self.begin = time.time()

        self.send_thread = threading.Thread(target=self.send)
        self.recv_thread = threading.Thread(target=self.recv)
        self.send_thread.start()
        self.recv_thread.start()

        start = time.time()
        while not self.state:
            if time.time() - start > 3:
                self.state = 'master'
        else:
            print('time out 3 second ' + '=' * 50 + self.state)
        pass

    def send(self):
        """"
        1.发送自己每走一步的位置给服务器。
        2.需要加锁。
        3.如果是服务器需要在一定时间内将所有数据发送给客户端。
        """
        if self.state is None:
            for _ in range(3):
                self.sock.sendto(b'master,', self.ADDRESS)
                time.sleep(0.5)
        elif self.state == 'master':
            pass
        elif self.state == 'slave':
            pass

    def recv(self):
        """
        1.从客户端接收每一步的位置。
        2.需要加锁。
        """
        while 1:
            data, addr = self.sock.recvfrom(1024)
            print(data, addr)
            self.sock.sendto(b'111', addr)
        pass

    pass


s = SnakeSock()